package com.ruoyi.framework.config.mqtt;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @description mqtt订阅
 */
@Component
@Configuration
@Data
@Slf4j
@ConfigurationProperties("mqtt")
public class MqttConfiguration {
    @Autowired
    private MqttCustomerClient mqttCustomerClient;
    private String host;
    private String clientId;
    private String username;
    private String password;
    private String topic;
    private int timeout;
    private int keepalive;

    @Bean
    public MqttCustomerClient getMqttCustomerClient() {
        long timestamp = System.currentTimeMillis();
        mqttCustomerClient.connect(host, clientId + timestamp, username, password, timeout,keepalive);
        // 以/#结尾表示订阅所有以mes开头的主题
        // mqttCustomerClient.subscribe("mes/#");
        mqttCustomerClient.subscribe("sea");
        return mqttCustomerClient;
    }

    /*
     * 定时任务发布，查询mqtt是否存活
     * @Scheduled(cron = "0 0/1 * * * ?")
     */

//    @Bean
    @Scheduled(cron = "0 0/1 * * * ?")
    public void checkMqtt(){
        if(MqttCustomerClient.getClient().isConnected()){
            log.info("mqtt is alive");
        }else {
            log.info("mqtt is not alive");
            log.info("mqtt connecting...");
            long timestamp = System.currentTimeMillis();
            mqttCustomerClient.connect(host, clientId + timestamp, username, password, timeout,keepalive);
            mqttCustomerClient.subscribe("sea");
        }
    }
}
